package controllers;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import models.RatingMPS;
import models.SolutionSubmission;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;
import com.googlecode.objectify.Query;

public class ajxAddMPSServlet extends HttpServlet {
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		try{
			//resp.setContentType("text/xml");
			PrintWriter out = resp.getWriter();
	        UserService userService = UserServiceFactory.getUserService();
	        User user = userService.getCurrentUser(); 
			
			String SolID = req.getParameter("txtsol_id");
			if ( SolID == null ){
				resp.sendRedirect("/home.jsp?error=Solution id is null.");
			}
			Long lSolID = Long.parseLong(SolID);
			
			Objectify ofy = ObjectifyService.begin();
			SolutionSubmission SOL = ofy.get(SolutionSubmission.class, lSolID);
			SOL.setMpsCandidate(true);
			ofy.put(SOL);
	
			//RESET ALL THE OTHER ENTRIES TO INACTIVE AND APPEND THE NEW ONE
			Query<RatingMPS> q = ofy.query(RatingMPS.class).filter("solID", lSolID);
	   		for ( RatingMPS f : q.fetch() ) {
	    			f.setActive(false);
	    			ofy.put(f);
	   		}
			
	   		//ADD NEW RATING MPS
	   		RatingMPS MPS = new RatingMPS();
	   		MPS.setSolID(lSolID);
	   		MPS.setMpsON(new Date());
	   		MPS.setRatedBY(user.getEmail());
	   		MPS.setActive(true);
			ofy.put(MPS);
			
			resp.sendRedirect("/modules/default/display-solution.jsp?sol_id=" + SolID);
			//out.println("MPS selected succesfully!");
		} catch(Exception ee){
			ee.printStackTrace();
		}
	}
}
